package com.example.minzhengtong.ui

import android.Manifest
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Picture
import android.os.Build
import android.os.Bundle
import android.view.View
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.fragment.app.FragmentActivity
import com.example.minzhengtong.Const
import com.example.minzhengtong.Const.baseIp
import com.example.minzhengtong.HttpRequest
import com.example.minzhengtong.base.BaseA
import com.example.minzhengtong.data.UserBean
import com.example.minzhengtong.databinding.ActivityPersonalProveBinding
import com.example.minzhengtong.utils.LogUtil
import com.example.minzhengtong.utils.SnapShot
import com.example.minzhengtong.utils.SpUtil
import com.example.minzhengtong.utils.WUtils
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar
import com.permissionx.guolindev.PermissionX
import com.permissionx.guolindev.request.ExplainScope
import com.permissionx.guolindev.request.ForwardScope
import java.util.ArrayList

/**
 * created by WY on 2021/5/31.
 * 个人缴存证明
 */
class PersonalProveA : BaseA() {

    companion object{
        fun enterThis(context: Context){
            val intent = Intent(context,PersonalProveA::class.java)
            context.startActivity(intent)
        }
    }

    private lateinit var binding : ActivityPersonalProveBinding

    private val initUrl = "${baseIp}prove.html?token=${SpUtil.getInstance().getString(Const.TOKEN)}"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        overridePendingTransition(0,0)
        binding = ActivityPersonalProveBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setToolBarVisiabale(false)

        ImmersionBar.with(this).titleBar(binding.titleBar).statusBarDarkFont(true).init()

        if (SpUtil.getInstance().existKey(Const.USER_BEAN)){
            val bean = SpUtil.getInstance().getObject(Const.USER_BEAN) as UserBean
            bean.data.apply {
                binding.account.text = "个人公积金账户：${uzh}"
            }
        }else{
            HttpRequest().detail(baseContext)
        }
        showDialog(false)
        Thread{
            Thread.sleep(1000)
            runOnUiThread {
                binding.containerImage.visibility = View.VISIBLE
                hideDialog()
            }
        }.start()

        binding.save.setOnClickListener {
            initPermission()
        }

        initWeb()

    }

    private fun initWeb(){
        val settings = binding.webview.settings
        settings.apply {
            javaScriptEnabled = true
            builtInZoomControls = true
            domStorageEnabled = true
            displayZoomControls  = false
            cacheMode = WebSettings.LOAD_NO_CACHE
        }

        //系统版本不小于5.0
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            WebView.enableSlowWholeDocumentDraw()
        }
        binding.webview.apply {
            settings.loadWithOverviewMode = true
            webViewClient = object : WebViewClient(){
                override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
//                view.loadUrl(url)
//                return super.shouldOverrideUrlLoading(view, url)
                    if (Build.VERSION.SDK_INT < 26) {
                        view.loadUrl(url)
                        return true
                    } else {
                        return false
                    }
                }

                override fun onPageFinished(view: WebView, url: String) {
                    super.onPageFinished(view, url)
                }
            }
            loadUrl("${initUrl}&account=${userBean?.data?.uzh}")
        }
    }

    override fun requestSuccess(json: String) {
        super.requestSuccess(json)
        val bean = Gson().fromJson(json, UserBean::class.java)
        bean.data.apply {
            binding.account.text = "个人公积金账户：${uzh}"
        }
    }

    private fun initPermission(){
        val permissions: MutableList<String> =
            ArrayList()
        permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        PermissionX.init(baseContext as FragmentActivity).permissions(permissions)
            .onExplainRequestReason { scope: ExplainScope, deniedList: List<String?>? ->
                //向用户解释请求权限的意图
                scope.showRequestReasonDialog(
                    deniedList,
                    "需要读取存储权限才可以存储图片",
                    "确定",
                    "取消"
                )
            }
            .onForwardToSettings { scope: ForwardScope, deniedList: List<String?>? ->
                //用户永久拒绝权限后的跳转设置页面开启
                scope.showForwardToSettingsDialog(
                    deniedList,
                    "请到设置中开启读写存储权限",
                    "确定",
                    "取消"
                )
            }
            .request { allGranted: Boolean, grantedList: List<String?>?, deniedList: List<String?>? ->
                if (allGranted) {
                    //获取到相册和权限
                    LogUtil.d("申请权限已获取")
//                    val saveBitmap = SnapShot(binding.webview,1f).apply()
                    val saveBitmap = captureWebView(binding.webview)
                    WUtils.saveImageToGallery(baseContext,saveBitmap)
                } else {
                    //用户拒绝了权限
                    LogUtil.d("申请权限已拒绝")
                }
            }
    }

    private fun  captureWebView(webView : WebView) : Bitmap {
        val snapShot : Picture = webView.capturePicture()
        val bitmap : Bitmap = Bitmap.createBitmap(snapShot.getWidth(), snapShot.getHeight(), Bitmap.Config.ARGB_8888)
         val canvas : Canvas = Canvas(bitmap)
        snapShot.draw(canvas)
        return bitmap
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(0,0)
    }

}